<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="maximum-scale=1.0,minimum-scale=1.0,user-scalable=0,width=device-width,initial-scale=1.0"/>
        <meta name="format-detection" content="telephone=no"/>
        <title>离线上传</title>
        <link rel="stylesheet" type="text/css" href="../../css/api.css"/>
        <link rel="stylesheet" type="text/css" href="../../css/aui.css" />
        <link rel="stylesheet" href="../../script/ccssoft/css/ccssoft-lite.css" />
        <link rel="stylesheet" type="text/css" href="./picOfflineUploadDetail.css" />
    </head>
    <body>
        <script id="picListId-template" type="text/x-dot-template">
            {{ for(var i=0, len=it.length; i < len; i++) {}}
            <div class="cardDiv" pid="{{=it[i].id}}" projectId="{{=it[i].projectid}}" imgpath="{{=it[i].imgpath}}" <!--onclick="getPhoto({{=i}})-->">
            <div class="cardLabel"><img class="aui-img-object aui-pull-left" src="{{=it[i].imgpath}}" height="73" width="48" onclick="openImg('{{=it[i].imgpath}}');"></div>
            <div class="cardCon">
            <div class="stationName"><font style="color:#ADADAD">名称:</font>{{=it[i].projectname}}</div>
            <div class="saveDate"><font style="color:#ADADAD">时间:</font>{{=it[i].savedate}}</div>
            </div>
            <div class="cardClose">
            <i class="aui-iconfont aui-icon-close" style="float:right;font-size:30px" onclick="removeImg('xunjian','{{=it[i].id}}')"></i>
            </div>
            </div>
            {{ } }}
        </script>
        <script id="billPicListId-template" type="text/x-dot-template">
            {{ for(var i=0, len=it.length; i < len; i++) {}}
            <div class="cardDiv" pid="{{=it[i].id}}" billid="{{=it[i].billid}}" imgpath="{{=it[i].imgpath}}" >
            <div class="cardLabel">
            <img class="aui-img-object aui-pull-left" src="{{=it[i].imgpath}}" height="73" width="48" onclick="openImg('{{=it[i].imgpath}}');"></img>
            </div>
            <div class="cardCon">
            <div class="billid item"><font>工单编号:</font>{{=it[i].billsn}}</div>
            <div class="stationid item"><font>站址名称:</font>{{=it[i].stationname}}</div>
            <div class="saveDate item"><font>拍照时间:</font>{{=it[i].savedate}}</div>
            </div>
            <div class="cardClose">
            <i class="aui-iconfont aui-icon-close" style="float:right;font-size:30px" onclick="removeImg('bill','{{=it[i].id}}')"></i>
            </div>
            </div>
            {{ } }}
        </script>
        <div id="wrap">
            <div class="aui-tab" style="position: absolute;top:0;left:0;">
                <ul class="aui-tab-nav" id="uploadPicTab">
                    <li class="active">
                        巡检图片
                    </li>
                    <li>
                        工单图片
                    </li>
                </ul>
            </div>
            <div id="tabBox" style="width:100%; overflow-y: scroll">
                <div id='tab1' class="tab" style="display: block; overflow-y:scroll">
                    <div id="picListId" style="overflow:auto;margin-bottom:55px;">
                        <div id="noData" class="noData" style="display:none;text-align:center;font-size:14px;margin-top:10px;height:40px;line-height:40px;">
                            ------暂无数据------
                        </div>
                        <div id="picListUl"></div>
                    </div>
                    <footer id="footer" style="height:50px;display:none;margin-bottom:55px;">
                        <div id="finishBottom" class="fixed_bottom">
                            <button class="outline center aui-btn aui-btn-success" onclick="uploadToServer('xunjian');">
                                一键上传
                            </button>
                        </div>
                    </footer>
                </div>
                <div id="tab2" class="tab" style="display: none">
                    <div id="billPicListId" style="overflow:auto;margin-bottom:55px;">
                        <div id="noBillData" class="noData" style="display:none;text-align:center;font-size:14px;margin-top:10px;height:40px;line-height:40px;">
                            ------暂无数据------
                        </div>
                        <div id="picBillListUl"></div>
                    </div>
                    <footer id="billFooter" style="height:50px;display:none;margin-bottom:55px;">
                        <div id="finishBottom" class="fixed_bottom">
                            <button class="outline center aui-btn aui-btn-success" onclick="uploadToServer('bill');">
                                一键上传
                            </button>
                        </div>
                    </footer>
                </div>
            </div>
        </div>
    </body>
    <script type="text/javascript" src="../../script/jquery-1.11.3.min.js"></script>
    <script type="text/javascript" src="../../script/api.js"></script>
    <script type="text/javascript" src="../../script/doT.min.js"></script>
    <script type="text/javascript" src="../../script/common.js"></script>
    <script type="text/javascript" src="../../script/debug.js"></script>
    <script type="text/javascript" src="../../script/config.js"></script>
    <script type="text/javascript" src="../../script/client.api.js"></script>
    <script type="text/javascript" src="../../script/aui-alert.js"></script>
    <script type="text/javascript" src="../../script/xunjian_db.js"></script>
    <script type="text/javascript">
        var user = null;
        var picInfo = picInfo || {};
        var uploadArray = [];
        apiready = function() {
            $('#tabBox').css('margin-top', $('.aui-tab').height());
            var projectId = "";
            user = $api.getStorage('user');
            $('#uploadPicTab li').click(function(index) {
                $(this).addClass('active').siblings().removeClass('active');
                $('#tab' + ($(this).index() + 1)).show().siblings().hide();
            });
            initPicList();
        };
        function initPicList() {
            db_init(function(ret, err) {
                if (ret) {
                    //获取巡检图片
                    db_getXunjianPic(user.userid, "", function(ret1, err) {
                        if (ret1 != "undefined" && ret1 != null) {
                            //判断是否有未上传的图片
                            if (ret1.length <= 0) {
                                $('#noData').show();
                            } else {
                                renderTemp('picListUl', 'picListId-template', ret1);
                                picInfo.xunjian = ret1;
                            }
                            hideMask();
                        } else {
                            $('#noData').show();
                            hideMask();
                            showToast("数据加载失败！");
                        }
                    });
                    //获取数据图片数量，如果不存在需上传图片，则把上传按钮屏蔽
                    db_getXunjianPicCount(user.userid, function(ret2, err) {
                        if (ret2 > 0) {
                            $("#footer").show();
                        }
                    });
                    //获取工单图片
                    db_getBillPic(user.userid, "", function(ret1, err) {
                        if (ret1 != "undefined" && ret1 != null) {
                            //判断是否有未上传的图片
                            if (ret1.length <= 0) {
                                $('#noBillData').show();
                            } else {
                                renderTemp('picBillListUl', 'billPicListId-template', ret1);
                                picInfo.bill = ret1;
                            }
                            hideMask();
                        } else {
                            $('#noBillData').show();
                            hideMask();
                            showToast("数据加载失败！");
                        }
                    });
                    //获取数据图片数量，如果不存在需上传图片，则把上传按钮屏蔽
                    db_getBillPicCount(user.userid, function(ret2, err) {
                        if (ret2 > 0) {
                            $("#billFooter").show();
                        }
                    });
                } else {
                    hideMask();
                    showToast("数据库初始化失败！");
                }
            });
        }

        /**
         *打开图片
         */
        function openImg(imgPath) {
            window.event.stopPropagation();
            showlog("openImg:" + imgPath);
            var module = api.require('imageBrowser');
            module.openImages({
                imageUrls : [imgPath],
                showList : false
            });
        }

        function uploadToServer(name) {
            if (curNetEnvironment()) {
                uploadImg(name);
            } else {
                api.confirm({
                    title : '网络提醒',
                    msg : '当前网络不是WiFi，是否继续上传？',
                    buttons : ['确定', '取消']
                }, function(ret, err) {
                    if (ret.buttonIndex == 1) {
                        uploadImg(name);
                    }
                });
            }
        }

        function uploadImg(name) {
            uploadArray = picInfo[name];
            if (uploadArray != null && typeof (uploadArray) != "undefined" && uploadArray.length > 0) {
                showMask("正在上传...");
                if (name == 'xunjian') {
                    while (uploadArray.length > 0) {
                        var data = uploadArray.shift();
                        var opts = {
                            isJson : true,
                            lon : data.lon,
                            lat : data.lat,
                            id : data.projectid,
                            phototime : data.savedate
                        };
                        uploadToRemote(opts, data, name);
                    }
                } else if (name == 'bill') {
                    while (uploadArray.length > 0) {
                        var data = uploadArray.shift();
                        var opts = {
                            isJson : true,
                            businessid : data.businessid,
                            billsn : data.billsn,
                            billid : data.billid,
                            imgDate : data.savedate,
                            userid : user.userid,
                            loginname : user.username
                        };
                        uploadToRemote(opts, data, name);
                    }
                }
            } else {
                showToast("暂无可上传图片!");
            }
        }

        //上传图片到服务器
        function uploadToRemote(opts, data, type) {
            var uploadFn = (type == 'bill') ? $client.uploadBillImage : $client.uploadProjectImage;
            uploadFn(opts, data.imgpath, function(ret, err) {
                delImg(type, data.id);
            });
        }

        //删除图片
        function removeImg(type, pid) {
            api.confirm({
                title : '图片信息将从缓存永久删除，确定删除?',
                buttons : ['确定', '取消']
            }, function(ret, err) {
                if (ret && ret.buttonIndex == 1) {
                    delImg(type, pid);
                }
            });
        }

        function delImg(type, pid) {
            var db_removeFn = (type == 'bill') ? db_removeBillPic : db_removeXunjianPic;
            uploadArray = picInfo[type];
            var fs = api.require('fs');
            //1.删除缓存图片
            fs.remove({
                path : $('[pid=' + pid + ']').attr('imgpath')
            }, function(ret, err) {
                if (ret.status || (err.code == 1)) {
                    if (err.code == 1) {
                        showlog('删除失败，该图片不存在！');
                    }
                    //2.删除本地数据库记录
                    db_removeFn(pid, function(status) {
                        if (status) {
                            //3.删除节点
                            $('[pid=' + pid + ']:visible').remove();
                            showlog('删除成功')
                            if (uploadArray.length == 0) {
                                hideMask();
                                $('.tab:visible').find('.noData').show().end().find('footer').hide();
                                api.execScript({
                                    name : 'home_win',
                                    frameName : 'footer_tab_1',
                                    script : 'setofflineUploadCount()'
                                });
                            }
                            showlog('删除本地数据库记录成功');
                            return true;
                        } else {
                            api.toast({
                                msg : '删除失败',
                                location : 'bottom'
                            });
                            showlog('删除本地数据库记录失败');
                            return false;
                        }
                    });
                    showlog('删除缓存成功:');
                    showlog(JSON.stringify(ret));
                } else {
                    api.toast({
                        msg : '删除失败！'
                    });
                    showlog('删除缓存失败:');
                    showlog(JSON.stringify(err));
                    return false;
                }
            });
        }

        //*该为临时版本的获取图片方法
        //      function getPhoto(index) {
        //          api.actionSheet({
        //              buttons : ['从相簿中选取']
        //          }, function(ret, err) {
        //              if (ret && ret.buttonIndex == 1) {
        //                  var picList = picInfo.xunjian;
        //                  var imgModel = picList[index];
        //                  api.getPicture({
        //                      sourceType : 'album',
        //                      encodingType : 'jpg',
        //                      mediaValue : 'pic',
        //                      quality : 20,
        //                      saveToPhotoAlbum : true
        //                  }, function(ret, err) {
        //                      var filePath = ret.data;
        //                      imgModel.imgpath = filePath;
        //                      $('#picListUl').empty();
        //                      renderTemp('picListUl', 'picListId-template', picInfo.xunjian);
        //                  });
        //              }
        //          });
        //      }
    </script>
</html>
